<template>
  <div class="shopcar">
    <!-- 商品列表 -->
    <div class="goods-list">
      <div class="mui-card" v-for="(item, i) in goodslist" :key="item.id">
        <div class="mui-card-content">
          <div class="mui-card-content-inner">
            <!-- 将开关与开关数组绑定 -->
            <mt-switch v-model="selected[i]"></mt-switch>
            <img class="thumb_img" :src="imgBaseUrl + item.thumb_path">
            <div class="info">
              <h4>{{item.title}}</h4>
              <div class="box">
                <span class="price">￥{{item.sell_price}}</span>
                <!-- initcount: 初始化的数量 -->
                <!-- id: 当前商品的Id -->
                <cartNumberBox :initcount="goodsCount[item.id]" :id="item.id"></cartNumberBox>

                <a href="#" @click.prevent="del(item.id)">删除</a>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
    <!-- 结算卡片 -->
    <div class="mui-card">
      <div class="mui-card-content">
        <div class="mui-card-content-inner">
          <div class="amount">
            <p>总计（不含运费）</p>
            <p>
              已勾选商品
              <span class="red">{{totalCount}}</span> 件 总价：
              <span class="red">￥{{totalPrice}}</span> 
            </p>
          </div>
          <mt-button type="danger">去结算</mt-button>
        </div>
      </div>
    </div>

    {{JSON.stringify(goodsCount)}}<br> {{JSON.stringify(selected)}}

  </div>
</template>

<script>
// 引入路径配置文件
import config from "../../js/globalConfig.js"
// 引入cart的numberbox
import cartNumberBox from "../common/cartNumberBox.vue"
export default {
  data() {
    return {
      goodslist:[],   //商品数组
      imgBaseUrl:config.imgBaseUrl,
      selected:[]
    }
  },
  created() {
    // 从服务器上获取商品数据
    this.getData();
  },
  methods: {
    getData() {
      var idsArr = [];
      // 获取store里所有商品的id组成的数组
      this.$store.state.car.map((item,i)=>{
        idsArr.push(item.id);
      })
      // console.log(idsArr);
      var idsStr = idsArr.join(",");
      // console.log(idsStr);

      // 如果购物车中没有商品，咋不发ajax请求，避免报错
      if(idsArr.length === 0) {
        return;
      }
      this.$http.get("api/goods/getshopcarlist/"+idsStr).then(res=>{
        // console.log(res.body);
        if(res.body.status === 0) {
          this.goodslist = res.body.message;
          // 根据商品信息数组，新生成一个对应的开关数组，初始化全为false
          for(var i = 0; i<this.goodslist.length; i++) {
            this.selected[i] = false;
          }
        }
      })
    },
    del(id) {
      // 触发store里的delGoodsFromId方法，删除对应id的商品信息
      this.$store.commit("delGoodsFromId",id);
      // 删除页面上对应id商品信息及对应开关信息
      this.goodslist.some((item,i,arr)=>{
        if(item.id === id) {
          arr.splice(i,1);
          this.selected.splice(i,1);
        }
      })
    }
  },
  computed: {
    // 将store上商品的id及数量映射为一个对象
    "goodsCount": function() {
      var idToCountObj = {};
      // 遍历store中的商品数据，将id为键，数量为值
      this.$store.state.car.forEach((item,i)=>{
        idToCountObj[item.id] = item.count;
      })
      return idToCountObj;
    },
    // 将选中的商品数量计算到已勾选总数量中
    "totalCount": function() {
      var total = 0;
      this.selected.forEach((item,i)=>{
        // 如果selected数组中为true,则对应的goodslist中商品的数量累加
        if(item) {
          // 根据索引找到去goodslist中找到id
          var id = this.goodslist[i].id;
          // console.log(id);
          total += this.goodsCount[id];
        }
      })
      return total;
    },
    "totalPrice": function() {
      var total = 0;
      this.selected.forEach((item,i)=>{
        // 如果selected数组中为true,则对应的goodslist中商品的数量累加
        if(item) {
          // 根据索引找到去goodslist中找到id及单价
          var id = this.goodslist[i].id;
          var price = parseInt(this.goodslist[i].sell_price);
          // console.log(id);
          total += this.goodsCount[id] * price;
        }
      })
      return total;
    }
  },
  // 将cartNumberBox注册为购物车页面的子组件
  components:{cartNumberBox}
}

</script>

<style lang="scss" scoped>
.shopcar {
  background-color: #eee;
  overflow: hidden;

  .goods-list {
    .mui-card-content-inner {
      display: flex;
      .thumb_img {
        width: 60px;
        height: 60px;
      }
      .info {
        flex: 1;
        h4 {
          font-size: 14px;
        }
        .box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .price {
            font-size: 16px;
            color: red;
          }
        }
      }
    }
  }

  .mui-card-content-inner {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .amount {
      flex: 1;
    }
    .red {
      color: red;
      font-size: 16px;
      font-weight: bold;
    }
  }
}
</style>
